import React from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import type { ConnectProps } from 'umi';
import { Redirect, connect } from 'umi';
// import { stringify } from 'querystring';
import type { ConnectState } from '@/models/connect';
import type { StaffInfoState, StaffInfoSourceState } from '@/models/user';
import { Message } from 'union-design';

type SecurityLayoutProps = {
  loading?: boolean;
  staffInfo?: StaffInfoState;
  staffInfoSource?: StaffInfoSourceState;
} & ConnectProps;

type SecurityLayoutState = {
  isReady: boolean;
  loginUrl: string | null;
};

class SecurityLayout extends React.Component<
  SecurityLayoutProps,
  SecurityLayoutState
> {
  state: SecurityLayoutState = {
    isReady: false,
    loginUrl: null,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'user/staffInfoFetch',
      })
        .then((res: any) => {
          // if (res && res.status && res.status === 'A0509') {
          //   dispatch({
          //     type: 'user/checkLoginUrl',
          //   })
          //     .then((resUrl: string) => {
          //       window.location.replace(resUrl);
          //     })
          //     .catch((msg: any) => {
          //       Message.warning(msg);
          //     });
          // }
          this.setState({
            isReady: true,
          });
        })
        .catch((error: any) => {
          // Message.warning(error);
        });
    }
  }
  // componentWillUnmount() {
  //   this.setState = (state, callback) => {
  //     return;
  //   };
  // }
  render() {
    const { isReady } = this.state;
    const { children, staffInfo } = this.props;
    const isLogin = staffInfo && staffInfo.loginName;
    // const queryString = stringify({
    //   redirect: window.location.href,
    // });
    if (!isLogin && !isReady) {
      return <PageLoading />;
    }
    if (!isLogin) {
      return <Redirect to={`/login`} />;
    }
    return children;
  }
}

export default connect(({ user }: ConnectState) => ({
  staffInfo: user.staffInfo,
  staffInfoSource: user.staffInfoSource,
  // loading: loading.models.user,
}))(SecurityLayout);
